/**
* @file osal.c
* @brief OSAL task run
* @details 
* @author huangbin
* @version V1.0.0
* @date 2025-04-25
* @copyright All documents are copyrighted by Shenzhen Xinlongwei Technology Co., LTD.
*            They may not be used for commercial purposes without permission
*/
#include "inc.h"
//设置一个事件
//task_id: 任务id
//event_flag: 事件标志
bool osalSetEvent( uint32_t task_id, uint32_t event_flag)
{
    if ( task_id < tasksCnt )
    {
        __IRQ_SAFE {
            //DISABLE_INTERRUPT();
            taskEventsTable[task_id] |= event_flag;
            //ENABLE_INTERRUPT();
        }
        return true;
    }
    return false;
}
//清除一个事件
//task_id: 任务id
//event_flag: 事件标志
bool osalClearEvent( uint32_t task_id, uint32_t event_flag)
{
    if ( task_id < tasksCnt )
    {
        //DISABLE_INTERRUPT();
        __IRQ_SAFE {
            taskEventsTable[task_id] &= ~(event_flag);
        }
        //ENABLE_INTERRUPT();
        return true;
    }
    return false;
}
void osalRunSystem ( void )
{
    uint8_t idx = 0;

    do
    {
        WatchDogFeed();
        if ( taskEventsTable[idx] )
            break;
    } while (++idx < tasksCnt);

    if ( idx < tasksCnt )
    {
        uint32_t events;
        {
            //DISABLE_INTERRUPT();
            __IRQ_SAFE {
                events = taskEventsTable[idx];
                taskEventsTable[idx] = 0;
            }
            //ENABLE_INTERRUPT();
        }
        
        WatchDogFeed();
        events = (tasksArr[idx])(idx, events);
        {
            //DISABLE_INTERRUPT();
            __IRQ_SAFE {
                taskEventsTable[idx] |= events;
            }
            //ENABLE_INTERRUPT();
        }
    }
}

void OsalInit(void)
{
    osalTimerInit();
    osalTasksInit();      // Init the OSAL Task
}

